package tg.edu.fhh.demo.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import tg.edu.fhh.demo.custom.BaseService;
import tg.edu.fhh.demo.entity.SysRole;
import tg.edu.fhh.demo.entity.SysUser;
import tg.edu.fhh.demo.repository.SysUserRepository;
import tg.edu.fhh.demo.security.User2;

@Service
public class SysUserService extends BaseService<SysUser, Integer>  implements UserDetailsService{
    @Autowired  
	private SysUserRepository userDAO ;
	public SysUser login(String username, String pwd) {
		return userDAO.findByUsernameAndPassword(username,pwd);
	}
	@Override
	public 
	UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      SysUser user= userDAO.findByUsername(username);
		if(user==null) {
			throw  new UsernameNotFoundException(username);
		}
		List<GrantedAuthority> authorities=new ArrayList<>();
		List<SysRole> roles = user.getRoles();
		for (SysRole role : roles) {
			authorities.add(new SimpleGrantedAuthority(role.getCode()));
		}
		return new User2(user.getUsername(),user.getPassword(),user.getName(),authorities);
	} 
	// public static void main(String[] args) {
//		  BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
//	 	 String encode="$2a$10$2Kr/Xwop70F5PhJPNA9mNOaV/rCDLG7TWRHqolgNILlZn2hq2TgUC";
	// System.out.println((encoder.matches("1234", encode)));	
		//  BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
	 	 //String encode=encoder.encode("1234");
	 	 //System.out.println(encode);
	  //}
}
